package com.evildog.workspace.file.upload.decorator;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.evildog.workspace.common.util.SpringContextHolder;
import com.evildog.workspace.common.util.WsAssert;
import com.evildog.workspace.file.convert.DocConvert;
import com.evildog.workspace.file.entity.Bucket;
import com.evildog.workspace.file.entity.Doc;
import com.evildog.workspace.file.enums.FileCustomExceptionDesc;
import com.evildog.workspace.file.service.BucketService;
import com.evildog.workspace.file.service.DocService;
import com.evildog.workspace.file.upload.object.VirtualFileDTO;
import com.evildog.workspace.file.upload.uploader.FileUploader;
import lombok.AllArgsConstructor;

import java.io.InputStream;

/**
 * 文件上传后，将文件保存至数据库
 */
@AllArgsConstructor
public class DbFileUploadDecorator extends FileUploadDecorator {

    private final FileUploader fileUploader;

    @Override
    public VirtualFileDTO upload(InputStream inputStream, String originalName, String folder) {
        WsAssert.hasText(folder, FileCustomExceptionDesc.FOLDER_NOT_HAS_TEXT);
        VirtualFileDTO virtualFileDTO = fileUploader.upload(inputStream, originalName, folder);

        DocService docService = SpringContextHolder.getBean(DocService.class);
        BucketService bucketService = SpringContextHolder.getBean(BucketService.class);

        Bucket bucket = bucketService.getOne(Wrappers.<Bucket>lambdaQuery()
                .select(Bucket::getId)
                .eq(Bucket::getName, folder)
        );

        WsAssert.notNull(bucket, FileCustomExceptionDesc.BUCKET_NOT_EXIST);

        Doc doc = DocConvert.INSTANCE.convert(virtualFileDTO);
        doc.setBucketId(bucket.getId());
        docService.save(doc);

        return virtualFileDTO;
    }

    @Override
    public boolean remove(String relativePath) {
        return fileUploader.remove(relativePath);
    }
}
